package com.xuexi.controller;

import com.easygo.utils.FastDFSClient;
import com.easygo.utils.MessageResults;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/*
* 文件上传的控制器
* */
@Controller
@Scope("prototype")
public class FileUploadController {

    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @RequestMapping("file_upload")
    @ResponseBody
    public MessageResults uploadImg(MultipartFile file){
        //文件上传的逻辑代码写在这个位置
        //1、获取上传的文件名
        String filename = file.getOriginalFilename();
        System.out.println("上传的原始文件名是："+filename);
        //2、获取上传的文件的后缀名
        String exename = filename.substring(filename.lastIndexOf("."));
        System.out.println("文件的扩展名是："+exename);
        //获取工具类,配置文件
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
            //上传文件,url返回上传成功的地址
            String url = fastDFSClient.uploadFile(file.getBytes(), exename);
            //这个地址不全，还需要拼接全地址
            String fullPath = FILE_SERVER_URL+url;
            return new MessageResults(200,fullPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MessageResults(500,null);
    }
}
